package luren.king.wechatlite.utils;

import android.Manifest;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import luren.king.wechatlite.R;

public class NotificationHelper {

    private static final String CHANNEL_ID = "channel_id";
    private static final int NOTIFICATION_ID = 123;

    public static void sendNotification(Context context, String title, String content) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 创建通知频道名称
            CharSequence name = "Channel Name";
            // 创建通知频道描述
            String description = "Channel Description";
            // 设置通知频道重要性
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            // 创建通知频道
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            // 设置通知频道描述
            channel.setDescription(description);
            // 获取通知管理器
            NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
            // 创建通知频道
            notificationManager.createNotificationChannel(channel);
        }

        // 创建通知构建器
        NotificationCompat.Builder builder = new NotificationCompat
                .Builder(context, CHANNEL_ID)
                .setSmallIcon(R.drawable.wechat) // 设置通知小图标
                .setContentTitle(title) // 设置通知标题
                .setContentText(content) // 设置通知内容
                .setPriority(NotificationCompat.PRIORITY_DEFAULT); // 设置通知优先级

        // 获取兼容的通知管理器
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
        // 检查是否已获得发送通知的权限
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
            // TODO: 考虑调用
            // 在此处请求缺失的权限，然后覆盖
            // 以处理用户授予权限的情况。请参阅 ActivityCompat#requestPermissions 的文档以获取更多详细信息。
            Toast.makeText(context, "有新消息到来，请授予发送通知的权限", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts("package", context.getPackageName(), null);
            intent.setData(uri);
            context.startActivity(intent);
            return;
        }
        // 发送通知
        notificationManager.notify(NOTIFICATION_ID, builder.build());
    }

}

